//
//  URAlertViewConroller.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/10/20.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class URAlertViewConroller: NSViewController {
    
    var fileSize:Double = 17.0
    
    var isDownloadFinish:Bool = false
    var request: DownloadRequest?

    let downUrl = FileManager.default.urls(for: FileManager.SearchPathDirectory.desktopDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)[0]
    var urlString =  "https://www.1meeting.cn/mac/1meeting.dmg"
    
    override func loadView() {
        let view = NSView.init(frame: NSRect.init(origin: CGPoint.zero, size: CGSize.init(width: 420, height: 130)))
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(230).cgColor
        self.view = view
    }
    
    convenience init(urlString:String?) {
        self.init()
        if let string = urlString {
            self.urlString = string
        }
        self.setupUI()
        self.loadData()
    }
    
    
    override func viewWillAppear() {
        super.viewWillAppear()
        self.refreshrtingWindow()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func loadData() {
        self.updateButtom.becomeFirstResponder()
        self.downLoad(url: self.urlString)
    }
    
    func setupUI() {
        self.view.addSubview(iconImage)
        iconImage.snp.makeConstraints { (make) in
            make.width.height.equalTo(64)
            make.top.left.equalTo(20)
        }
        
        self.view.addSubview(rightView)
        rightView.snp.makeConstraints { (make) in
            make.left.equalTo(iconImage.snp.right).offset(20)
            make.right.equalTo(-20)
            make.top.bottom.equalToSuperview()
        }
        
        self.rightView.addSubview(ktitle)
        ktitle.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.left.equalToSuperview()
            make.top.equalTo(20)
        }
        
        self.rightView.addSubview(accessoryView)
        accessoryView.snp.makeConstraints { (make) in
            make.height.equalTo(32)
            make.width.left.equalToSuperview()
            make.top.equalTo(ktitle.snp.bottom).offset(10)
        }
        
        self.rightView.addSubview(updateButtom)
        updateButtom.snp.makeConstraints { (make) in
            make.width.equalTo(90)
            make.right.equalToSuperview()
            make.bottom.equalTo(-20)
        }
        
        
        self.accessoryView.addSubview(indicator)
        indicator.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(10)
        }
        
        self.accessoryView.addSubview(loadLab)
        loadLab.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.width.equalTo(100)
            make.left.equalTo(0)
            make.height.equalTo(18)
        }
    }
    
    func refreshrtingWindow() {
        self.view.window?.standardWindowButton(NSWindow.ButtonType.closeButton)?.isHidden = true
        self.view.window?.standardWindowButton(NSWindow.ButtonType.miniaturizeButton)?.isHidden = true
        self.view.window?.standardWindowButton(NSWindow.ButtonType.zoomButton)?.isHidden = true
        self.view.window?.styleMask = [.titled]
        self.title = "软件更新"
    }
    
    
    
    lazy var indicator: NSProgressIndicator = {
        let view = NSProgressIndicator.init(frame: NSRect.zero)
        view.style = NSProgressIndicator.Style.bar
        view.controlSize = .regular
        view.isIndeterminate = false
        view.minValue = 0.0
        view.maxValue = 100.0
        view.doubleValue = 0.0
        return view
    }()
    
    lazy var loadLab: NSLabel = {
        let lab = NSLabel.label(title: "0.0M/\(fileSize)M", textColor: NSColor.black, font: NSFont.systemFont(ofSize: 14))
        return lab
    }()
    
    lazy var accessoryView: NSView = {
        let view = NSView.init(frame: NSRect.init(x: 0, y: 0, width: 300, height: 32))
        return view
    }()
    
    lazy var rightView: NSView = {
        let view = NSView.init()
        return view
    }()
    lazy var iconImage: NSImageView = {
        let imageV = NSImageView.init(image: NSImage.image(name:"ic_logo_blue") ?? NSImage.init())
        return imageV
    }()
    
    lazy var ktitle: NSLabel = {
        let lab = NSLabel.label(title: "正在下载更新", textColor: color_gray(0), font: NSFont.boldSystemFont(ofSize: 14))
        lab.sizeToFit()
        return lab
    }()
    
    lazy var updateButtom: NSButton = {
        let btn = NSButton.init()
        btn.title = "取消"
        btn.bezelStyle = .rounded
        btn.setButtonType(NSButton.ButtonType.pushOnPushOff)
        btn.state = .on
        btn.font = NSFont.systemFont(ofSize: 13)
        btn.keyEquivalent = "\r"
        btn.target = self
        btn.action = #selector(updateButtomAction(sender:))
        btn.sizeToFit()
        return btn
    }()
    
    @objc func updateButtomAction(sender:NSButton) {
        if self.isDownloadFinish {
            XQProcess.restartToFile(fileName: self.urlString.lastPathComponent, basicPath: nil)
        }else {
            if self.request != nil {
                self.request?.suspend()
            }
            if File.isfileExists(path: downUrl.absoluteString) == false {
                File.removeFilePath(path: downUrl.absoluteString)
            }
        }
        self.view.window?.close()
    }
    
    
    func downLoad(url:String) {
        self.request = NetworkTool.download(urlString: url, fileBaseUrl: self.downUrl, closure: { (progress) in
            self.indicator.doubleValue = (progress*100)
            let s = String.init(format: "%.2f", (progress*self.fileSize))
            self.loadLab.stringValue = s+"M/"+"\(self.fileSize)M"
            print("正在下载。。。。")
        }) { (data) in
            self.loadLab.stringValue = "\(self.fileSize)M/\(self.fileSize)M"
            self.updateButtom.title = "点击安装".localized()
            self.ktitle.stringValue = "下载完成，文件已保存到桌面".localized()
            self.isDownloadFinish = true
            self.request = nil
            print("完成")
        }
    }
    
    
    
}
